package com.example.service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;

import android.util.Xml;

import com.example.model.Order;

public class xmlService {
	public List<Order> getOrders(InputStream inputStream) throws XmlPullParserException, IOException{
		List<Order> orders = null;
		XmlPullParser pullParser = Xml.newPullParser();
		pullParser.setInput(inputStream, "UTF-8");
		int eventType=pullParser.getEventType();
		Order order = null;
		while (eventType != XmlPullParser.END_DOCUMENT) {
			switch (eventType) {
			case XmlPullParser.START_DOCUMENT:
				orders = new ArrayList<Order>();
				break;
			case XmlPullParser.START_TAG:
				if ("Order".equals(pullParser.getName())) {
					order = new Order();
					int id = Integer.parseInt(pullParser.getAttributeValue(0));
					order.setId(id);
				}else if("name".equals(pullParser.getName())){
					String name = pullParser.nextText();
					order.setName(name);
				}else if("desc".equals(pullParser.getName())){
					String desc = pullParser.nextText();
					order.setDesc(desc);
				}
				break;
			
			case XmlPullParser.END_TAG:
				if("Order".equals(pullParser.getName())){
					orders.add(order);
				}
			}
			eventType=pullParser.next();
		}
		return orders;
	}
	
	public void save(List<Order> orders,FileOutputStream out) throws IllegalArgumentException, IllegalStateException, IOException{
		XmlSerializer serializer = Xml.newSerializer();
		serializer.setOutput(out,"UTF-8");
		serializer.startDocument("UTF-8",true);
		serializer.startTag(null, "Orders");
		for(Order order:orders){
			serializer.startTag(null, "Order");
			serializer.attribute(null, "id", order.getId().toString());
			
			serializer.startTag(null, "name");
			serializer.text(order.getName());
			serializer.endTag(null, "name");
			
			serializer.startTag(null, "desc");
			serializer.text(order.getDesc());
			serializer.endTag(null, "desc");
			
			serializer.endTag(null, "Order");
		}
		serializer.endTag(null, "Orders");
		serializer.endDocument();
	}
}
